package com.example.demo.util;

import com.baidu.aip.imageclassify.AipImageClassify;
import com.example.demo.model.Dishes;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.stereotype.Component;

import java.util.HashMap;

@Component
public class RecognizeUtil {
    // 设置APPID/AK/SK
    private static final String APP_ID = "52007337";
    private static final String API_KEY = "RlAb5sg0ZGuOcWhBN9G8WD44";
    private static final String SECRET_KEY = "VYHjhGxehxUaQv9rr6HrtHGOcNpqdpW1";

    public static Dishes Recognize(String imagePath) {
        // 初始化一个AipImageClassify
        AipImageClassify client = new AipImageClassify(APP_ID, API_KEY, SECRET_KEY);

        Dishes dish=null;
        try {
            // 调用接口
            HashMap<String, String> options = new HashMap<String, String>();
            options.put("top_num", "3");
            options.put("filter_threshold", "0.7");
            options.put("baike_num", "5");
            JSONObject res = client.dishDetect(imagePath,options);
//            JSONObject res = client.dishDetect("D:\\software\\baiduSDK\\test\\th.jpg",options);
            System.out.println(res.toString(2));  // 打印结果

            // 获取百度百科链接、描述和图片
            if (res.has("result")) {
                JSONArray resultArray = res.getJSONArray("result");
                if (resultArray.length() > 0) {
                    JSONObject firstDish = resultArray.getJSONObject(0);
                    // 获取菜品描述信息
                    JSONObject baikeInfo = firstDish.getJSONObject("baike_info");
                    String name = firstDish.optString("name");
                    String  calorie = firstDish.optString("calorie");
                    int calorie1=Integer.parseInt(calorie);
                    String description = baikeInfo.optString("description");
                    String baikeUrl = baikeInfo.optString("baike_url");
                    String imageUrl = baikeInfo.optString("image_url");
//                    Long dishId = 22L;
                    dish= new Dishes(name,description,imageUrl);
                    System.out.println("百度百科链接：" + baikeUrl);
                    System.out.println("百度百科描述：" + description);
                    System.out.println("百度百科图片：" + imageUrl);
                }
            }
        } catch (org.json.JSONException e) {
            e.printStackTrace();  // 打印异常信息
        }
        return dish;
    }
}


